using System;
using System.Collections.Generic;

namespace DuplexTransformers
{
    public class ListTransformer<TLeft, TRight> : ITransformer<IList<TLeft>, IList<TRight>>
    {
        protected ITransformer<TLeft, TRight> ItemTransformer;

        public ListTransformer(ITransformer<TLeft, TRight> itemTransformer)
        {
            ItemTransformer = itemTransformer;
        }

        protected ListTransformer()
        {
        }

        public IList<TRight> Invoke(IList<TLeft> src, IList<TRight> current)
        {
            while (current.Count > src.Count) current.RemoveAt(current.Count - 1);
            for (var index = 0; index < src.Count; index++)
            {
                var left = src[index];
                var right = index < current.Count - 1 ? current[index] : Activator.CreateInstance<TRight>();
                current.Add(ItemTransformer.Invoke(left, right));
            }
            return current;
        }

        public IList<TLeft> Invoke(IList<TRight> src, IList<TLeft> current)
        {
            while (current.Count > src.Count) current.RemoveAt(current.Count - 1);
            for (var index = 0; index < src.Count; index++)
            {
                var right = src[index];
                var left = index < current.Count - 1 ? current[index] : Activator.CreateInstance<TLeft>();
                current.Add(ItemTransformer.Invoke(right, left));
            }
            return current;
        }
    }
}